<template>
	<scroll-view scroll-y @scrolltolower="loadMore" style="height: 100vh;">
		<view class="list">
			<view class="main" v-if="tabIndex==0">
				<view class="example-body">
					<uni-datetime-picker :start="getThreeDaysAgo()" v-model="range1" type="daterange"
						@change="changeLog2($event)" />
				</view>
				<!-- 列表内容 -->
				<yt-order-list class="item" @change="orderListChangeId" :orderList="orderList" @Transfer="Transfer"
					@jieOrder="jieOrder" @callUser="callUser">
				</yt-order-list>
				<view class="bottom">
					<view class="left">
						<button size="default" type="primary">订单数量 {{total}}</button>
					</view>
					<div v-if="nextLevelUserlist.length">
						<view class="right" v-if="checkedIdList.length">
							<picker @change="bindPickerChange" :value="index" :range="nextLevelUserlist"
								:range-key="'nickName'">
								<button size="default" type="primary">分配订单 {{checkedIdList.length}}</button>
							</picker>
						</view>
						<view class="right" v-else>
							<button size="default" type="primary">分配订单 0</button>
						</view>
					</div>

				</view>
			</view>
			<view class="main" v-else>
				<view class="example-body">
					<uni-datetime-picker v-model="range" type="daterange" @change="changeLog($event)" />
				</view>
				<view class="num">
					订单数量：{{orderNum}}
				</view>
			</view>
			<jx-tab @tabTap="tabTap"></jx-tab>
			<!-- <view class="uni-input">{{array[index]}}</view> -->
		</view>
	</scroll-view>
</template>

<script>
	import api from '@/utils/request.js'
	import {
		formatDate
	} from '@/utils/conmon.js'
	export default {
		data() {
			return {
				oldDate: '',
				value: [],
				index: 0,
				isAll: false,
				nextLevelUserlist: [],
				nextLevelUserObj: {},
				range: [formatDate(new Date(), 'yyyy-MM-dd'), formatDate(new Date(), 'yyyy-MM-dd')],
				// orderList: [{
				// 	orderId: '20240407',
				// 	title: '周永兰 19270069306',
				// 	status: 2, //3:已完成 2:进行中 否则待接单
				// 	cAddress: '广东/东莞市/大朗镇',
				// 	mAddress: '长宏新城二街121号',
				// 	time: '广电',
				// 	km: '0.6km',
				// 	checked: false
				// }],
				orderList: [],
				checkedIdList: [],
				tabIndex: 0,
				pageInfo: {
					pageNum: 1,
					pageSize: 10
				},
				noload: false,
				total: 0,
				range1: [formatDate(new Date(), 'yyyy-MM-dd'), formatDate(new Date(), 'yyyy-MM-dd')],
				orderNum:0,

			}
		},
		computed: {
			// 计算是否全选
			selectNum() {
				let num = 0;
				this.orderList.forEach(v => {
					if (v.checked) {
						num += 1
					}

				})
				return num
			}
		},
		mounted() {
			this.getInfo();
			this.getOrderUserList()
		},
		methods: {
			orderCount(){
				let userInfoData = uni.getStorageSync('userInfoData')
				let data={
					userId:userInfoData.user.userId
				}
				let userType
				if (userInfoData.roles.includes('orderManager')) {
					data.userType=1
				}else if(userInfoData.roles.includes('businessPosition')){
					data.userType=2
				}else if(userInfoData.roles.includes('deliveryPost')){
					data.userType=3
				}
				data['params[beginTime]'] = this.range[0]
				data['params[endTime]'] = this.range[1]
				api.request({
					url: '/system/orders/orderCount',
					method: 'get',
					data: data
				}).then(res => {
					// console.log(res)
					if (res.code == 200) {
						this.orderNum=res.data
					}
				})
			},
			getThreeDaysAgo() {
				const now = new Date();
				const threeDaysAgo = new Date(now);
				threeDaysAgo.setDate(now.getDate() - 3);

				return formatDate(threeDaysAgo, 'yyyy-MM-dd');
			},
			getOrderUserList() {
				api.request({
					url: '/system/user/nextLevelUserlist',
					method: 'get',
					data: {
						userId: uni.getStorageSync('userInfoData').user.userId
					}
				}).then(res => {
					// console.log(res)
					if (res.code == 200) {
						this.nextLevelUserlist = res.rows
					}
				})
			},
			loadMore() {
				if (this.noload) {
					return
				}
				this.pageInfo.pageNum++
				this.getPage()
			},
			getInfo() {
				api.request({
					url: '/getInfo',
					method: 'get',
				}).then(res => {
					// console.log(res)
					if (res.code == 200) {
						uni.setStorageSync('userInfoData', res)
						this.getPage()
						this.orderCount()
					}
				})
			},
			getPage() {
				let data = this.pageInfo
				data['params[beginTime]'] = this.range1[0]
				data['params[endTime]'] = this.range1[1]
				let userInfoData = uni.getStorageSync('userInfoData')
				if (userInfoData.roles.includes('orderManager')) {
					data['params[isOrderManager]'] = '1'
				} else {
					data.userId = userInfoData.user.userId
				}
				api.request({
					url: '/system/orders/list',
					method: 'get',
					data: data
				}).then(res => {
					// console.log(res)
					if (res.code == 200) {
						this.total = res.total
						this.orderList.push(...res.rows)
						console.log(this.orderList);
						if (res.total == this.orderList.length) {
							this.noload = true
						}
					}
				})
			},
			tabTap(obj) {
				this.tabIndex = obj.index
			},
			orderListChangeId: function(idList) {
				console.log(idList)
				this.checkedIdList = idList;
			},
			bindPickerChange: function(e) {
				var vm = this;
				this.index = e.detail.value;
				this.nextLevelUserObj = this.nextLevelUserlist[this.index];
				// return
				const data = {
					orderIds: this.checkedIdList.join(','),
					userId: this.nextLevelUserObj.userId,
					userName: this.nextLevelUserObj.userName
				}
				api.request({
					url: '/system/orders/assignOrders',
					method: 'post',
					data
				}).then(res => {
					// console.log(res)
					if (res.code == 200) {
						uni.showToast({
							title: '成功给'+this.nextLevelUserObj.userName+'分配'+this.checkedIdList.length+'条订单',
							duration: 2000
						});
						this.checkedIdList=[]
						this.orderList=[]
						vm.getPage()
					}
				})
			},
			all() {
				this.checkedIdList = []
				if (!this.isAll) {
					this.orderList.forEach(v => {
						v.checked = true
					})
					this.isAll = true
				} else {
					this.orderList.forEach(v => {
						v.checked = false
					})
					this.isAll = false
				}
				console.log(this.orderList);
				this.orderList.forEach(item => {
					this.checkedIdList.push(item.id)
				})
			},
			change(e) {
				console.log('e:', e.detail.value);
			},
			/**
			 * @method Transfer
			 * 订单转派
			 * @param {Object} id
			 */
			Transfer(id) {
				console.log("转派", id);
				// 高德地图
				const amapUrl = `https://uri.amap.com/marker?name=广州市`;
				// 尝试打开地图APP，失败则跳转网页版
				window.location.href = amapUrl;

			},
			/**
			 * @method jieOrder
			 * 接单
			 * @param {Object} id
			 */
			jieOrder(id) {
				console.log("接单", id);
			},
			/**
			 * @method callUser
			 * 联系
			 * @param {Object} id
			 */
			callUser(id) {
				console.log("联系", id);
				uni.makePhoneCall({
					phoneNumber: '13113981593' //仅为示例
				});
			},
			changeLog(e) {
				this.range = e
				this.orderCount()
				// console.log('maskClick事件:', e);
			},
			changeLog2(e) {
				this.orderList=[]
				this.range1 = e
				this.getPage()
				// console.log('maskClick事件:', e);
			}
		}
	}
</script>
<style lang="scss" scoped>
	* {
		box-sizing: border-box;
	}

	.list {
		background: #FFF;
		padding: 20rpx;
		min-height: 100vh;

		.main {
			.item {
				margin-top: 20upx;
			}
		}

		// padding-bottom: 120upx;
		.num {
			padding: 20upx;
		}

		.bottom {
			width: 100%;
			position: fixed;
			bottom: 120upx;
			left: 0;
			display: flex;
			justify-content: space-around;

			// .left {
			// 	width: 45%;
			// 	margin-left: 20upx;
			// }

			// .right {
			// 	width: 45%;
			// 	margin-right: 20upx;
			// }
		}

		::v-deep .uni-calendar__content {
			z-index: 998;
		}
	}
</style>